package com.zl.learning.io.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ChatClient {

    public static void main(String[] args) {
        new ChatClient().init();
    }

    private void init() {
        try {
            Socket socket = new Socket("127.0.0.1", 666);
            new Thread(() -> this.receiveMsg(socket)).start();
            Scanner scanner = new Scanner(System.in);
            for (String msg = scanner.nextLine(); !"exit".equals(msg); msg = scanner.nextLine()) {
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(msg.getBytes());
                outputStream.flush();
                System.out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void receiveMsg(Socket socket) {
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            while (true) {
                int len = inputStream.read(bytes);
                System.out.println(new String(bytes, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
